package site.qjdb.service.impl;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import site.qjdb.dao.CartDao;
import site.qjdb.pojo.Cart;
import site.qjdb.service.CartService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {
	@Resource
	private CartDao cartDao;

	@Override
	public void addCart(Cart cart) {
		cartDao.addCart(cart);
	}

	@Override
	public int findCartCount(Cart cart) {
		return cartDao.selectCartCount(cart);
	}

	/**
	 * 根据条件查找购物车项，没找到则返回null
	 * */
	@Override
	public List<Cart> findCartAll(Cart cart) {
		Map<String, Object> map = new HashMap<>();
		map.put("cart", cart);
		map.put("orderBy", "cart.time desc");
		List<Cart> cartList = cartDao.selectCartAll(map);
		// 只返回状态为1（通过）的商品
		removeCart(cartList);
		if(cartList == null || cartList.size() == 0) {
			return null;
		} else {
			return cartList;
		}
	}
	
	private void removeCart(List<Cart> cartList) {
		boolean isAllPass = true;
		for(int i = 0; i < cartList.size(); i++) {
			Cart _cart = cartList.get(i);
			if(_cart.getGoods().getState() != 1) {
				// 只显示通过的商品
				cartList.remove(i);
				isAllPass = false;
				break;
			}
		}
		if(!isAllPass) {
			removeCart(cartList);
		}
	}

	@Override
	public boolean deleteCart(Cart cart) {
		cart.setIsDel(0);
		int i = cartDao.selectCartCount(cart);
		if(i == 1) {
			// 设置删除
			cart.setIsDel(1);
			cartDao.updateCart(cart);
			return true;
		}
		return false;
		
	}

	@Override
	public boolean deleteCarts(List<Cart> cartList) {
		boolean flag = true;
		for(int i = 0; i < cartList.size(); i++) {
			Cart cart = cartList.get(i);
			cart.setIsDel(0);
			int c = cartDao.selectCartCount(cart);
			cart.setIsDel(1);
			if(c == 0) {
				flag = false;
				break;
			}
		}
		if(flag) {
			cartDao.updateCarts(cartList);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void modifyCart(Cart cart) {
		cartDao.updateCart(cart);
		
	}

}
